package com.lucenten.collect.gnss.handler.impl;

import cn.quevo.common.lang.DateFormatUtils;
import cn.quevo.common.lang.DateUtils;
import cn.quevo.common.lang.StringUtils;
import com.lucenten.collect.Context;
import com.lucenten.collect.gnss.entity.GnssFile;
import com.lucenten.collect.gnss.handler.AbstractGnssHandler;
import com.lucenten.collect.gnss.handler.GnssHandler;
import com.lucenten.collect.gnss.service.ObsErvationService;
import com.lucenten.collect.gnss.service.SatelliteStationService;
import com.lucenten.mq.SendJmsInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.LifecycleState;
import org.springframework.scheduling.annotation.Async;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

/**
 * 最后一步，清理掉临时数据
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2019/4/28 10:47
 * @Copyright 东方浩星（北京）传媒科技有限公司版权所有.All Rights Reserved.
 */
@Slf4j
public class CleanGnssHandler extends AbstractGnssHandler implements GnssHandler {

    public CleanGnssHandler(SatelliteStationService satelliteStationService, ObsErvationService obsErvationService) {
        super(satelliteStationService, obsErvationService);
    }

    @Async
    @Override
    protected boolean doProcess(GnssFile gnssFile) {
        if (!isDev) {
            this.deleteClear(gnssFile);
            if (StringUtils.isBlank(SOURCE_SUBS)) {
                for (String sub : SOURCE_SUBS) {
                    // 清空原始文件目录
                    this.deleteDirs(Paths.get(gnssFile.getSourceFile()).getParent().normalize().toString(),Paths.get(gnssFile.getRoot(),sub).normalize().toString());
                }
            }else {

            }
            // 清空临时O文件目录
            this.deleteDirs(Paths.get(super.getTempPath("o", gnssFile)).normalize().toString(),Paths.get(COLLECT_TMP,"o").normalize().toString());
            // 清空临时O INFO文件目录
            this.deleteDirs(Paths.get(super.getTempPath("stationInfo", gnssFile)).normalize().toString(),Paths.get(COLLECT_TMP,"stationInfo").normalize().toString());

            StringBuilder logs = new StringBuilder("线程名称:");
            logs.append(Thread.currentThread().getName());
            logs.append(";开始时间：").append(DateFormatUtils.format(Context.startDate, "yyyy/MM/dd HH:mm:ss.SSS"));
            logs.append(";截止时间：").append(DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss.SSS"));
            log.info(logs.toString());
        }else {
            System.out.println("START:" + DateFormatUtils.format(Context.startDate, "yyyy/MM/dd HH:mm:ss.SSS"));
            System.out.println("END  :" + DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss.SSS"));
            System.out.println("线程名" + Thread.currentThread().getName());
        }
        return true;
    }

    /**
     * 删除指定需要删除的文件
     *
     * @param gnssFile
     */
    private void deleteClear(GnssFile gnssFile) {
        if (StringUtils.isEmpty(gnssFile.getClearList())) {
            return;
        }
        for (String delFile : gnssFile.getClearList()) {
            try {
                if (Files.notExists(Paths.get(delFile))) {
                    continue;
                }
//                SendJmsInfo.sendGnssMq(17, Paths.get(delFile).getFileName().normalize().toString(), 0);
                Files.delete(Paths.get(delFile));
            } catch (IOException e) {
                SendJmsInfo.sendGnssMq(17, Paths.get(delFile).getFileName().normalize().toString(), 1);
                log.error("文件删除失败:["+delFile+"]",e);
            }
        }
    }
    /**
     * 清空目录
     * @param hourRoot
     * @param root
     */
    protected void deleteDirs(String hourRoot, String root) {
        try {
            File del = new File(hourRoot);
            if (del == null) {
                return;
            }
            if (del.listFiles() == null || del.listFiles().length == 0) {
                del.delete();
//                SendJmsInfo.sendGnssMq(17, del.getName(), 0);
                this.clear(new File(root));
                /*del = new File(root);
                if (del.listFiles() == null || del.listFiles().length == 0) {
                    del.delete();
                }*/
            }
        } catch (IOException e) {
            log.error("空目原始录清理失败" + e.toString(), e);
            SendJmsInfo.sendGnssMq(17, hourRoot, 1);
        }
    }

    protected void clear(File dir) throws IOException {
        File[] dirs = dir.listFiles();
        if (dirs == null || dirs.length == 0) {
            if (dir.isDirectory()) {
                dir.delete();
            }
            return;
        }
        for (int i = 0; i < dirs.length; i++) {
            if (dirs[i].isDirectory()) {
                clear(dirs[i]);
            }
        }
        /*if (dir.isDirectory()) {
            dir.delete();
        }*/
    }
}
